<?php

namespace backend\models;

/**
 * @author  shuang
 * @date    2016-11-16 8:23:26
 * @version V1.0
 * @desc    
 */
use common\models\UserTaskOperate;
use yii\behaviors\TimestampBehavior;
use Yii;
use frontend\models\WB_UserPayRecord;
use frontendm\models\WB_UserPayRecordHy;
use common\components\MTools;

class MY_UserTaskOperate extends UserTaskOperate {

    public static $complain = [
        0 => "投诉",
        1 => "投诉中",
        2 => "投诉成功",
        3 => "投诉失败",
        4 => "申诉中",
        5 => "申诉成功",
        6 => "申诉失败"
    ];

    /*
     * 设置表操作行为动作
     * return array
     */

    public function behaviors() {
        return[
            [
                'class' => TimestampBehavior::className()
            ]
        ];
    }

    /*
     * 查询投诉（申诉）任务
     * @params $comType  1 complain  2 appeal
     * @params $noAudit  true or false
     */

    public static function searchComplainTask($comType = 1, $noAudit = false) {
        if ($comType == 1) {
            $begin_value = 1;
            $end_value = 3;
            $complain = 1;
        } else {
            $begin_value = 4;
            $end_value = 6;
            $complain = 4;
        }
        $query = MY_UserTaskOperate::find()->leftJoin(["task" => MY_Task::tableName()], "me_user_task_operate.taskid=task.id");
        $query->leftJoin(["userprofile"=>  MY_UserProfile::tableName()],"me_user_task_operate.userid=userprofile.userid");
        $sort = Yii::$app->request->get("sort", "me_user_task_operate.created_at");
        $order = Yii::$app->request->get("order");
        $query->orderBy($sort . " " . $order);
        $query->select("task.title,userprofile.username,task.sample_figure,me_user_task_operate.*");
        $query->andFilterWhere(["like", "task.title", Yii::$app->request->get("search")]);
        $query->orFilterWhere(["like", "task.id", Yii::$app->request->get("search")]);
        $query->orFilterWhere(["like", "userprofile.username", Yii::$app->request->get("search")]);
        $query->orFilterWhere(["like", "complain_note", Yii::$app->request->get("search")]);
        if (!$noAudit) {
            $query->andFilterWhere(['between', 'is_complain', $begin_value, $end_value]);
        } else {
            $query->andWhere("is_complain=:is_complain", [":is_complain" => $complain]);
        }
        $countQuery = clone $query;
        $offset = Yii::$app->request->get("offset");
        $limit = Yii::$app->request->get("limit");
        $totalCount = $countQuery->count();
        $res = $query->offset($offset)->limit($limit)->asArray()->all();
        return ["total" => $totalCount, "data" => $res];
    }

    public static function getauditList($is_complain = null) {
        $query = MY_UserTaskOperate::find()->leftJoin(["task" => MY_Task::tableName()], "me_user_task_operate.taskid=task.id");
        $sort = Yii::$app->request->get("sort", "title");
        $order = Yii::$app->request->get("order");
        $query->orderBy($sort . " " . $order);
        $query->select("task.title,task.sample_figure,task_image,is_complain,complain_note,me_user_task_operate.created_at,me_user_task_operate.id,me_user_task_operate.taskid,me_user_task_operate.complain_at,me_user_task_operate.complain_audit_at,me_user_task_operate.appeal_at,me_user_task_operate.appeal_audit_at");
        $query->andFilterWhere(["like", "task.title", Yii::$app->request->get("search")]);
        $query->orFilterWhere(["like", "complain_note", Yii::$app->request->get("search")]);
        if ($is_complain) {
            $query->andFilterWhere(["in", "is_complain", "1,4"]);
        } else {
            $query->andWhere("is_complain != 0");
        }
        $countQuery = clone $query;
        $offset = Yii::$app->request->get("offset");
        $limit = Yii::$app->request->get("limit");
        $totalCount = $countQuery->count();
        $res = $query->offset($offset)->limit($limit)->asArray()->all();
        return ["total" => $totalCount, "data" => $res];
    }

    /*
     * 关联字典表  任务类型
     */

    public function getTaskID() {

        return $this->hasOne(MY_Task::className(), ['id' => 'taskid']);
    }

    /*
     * 投诉审核
     * @params $id
     * @params $is_complain
     * return boolean
     */

    public static function auditTask($id, $pass = true) {
        $model = MY_UserTaskOperate::findOne($id);
        if ($model->is_complain == 2 || $model->is_complain == 5) { //任务已经操作过了
            return false;
        }
        $now = time();
        if ($pass) {
            if($model->is_complain == 1){
//                if($now - $model->complain_at < 86400){
//                    return false;
//                }
                $model->is_complain = 2;
            }else{
                $model->is_complain = 5;
            }
            $model->complain_audit_at = time();
        } else {
            $model->is_complain = $model->is_complain == 1 ? 3 : 6;
            $model->appeal_audit_at = time();
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            if ($model->update()) {
                $taskmodel = MY_Task::findOne($model->taskid);
                if ($model->is_complain === 2) {
                    //返还商户
                    WB_UserPayRecord::createRecord($model->taskuserid, MTools::getTaskPrice($taskmodel->task_price_id), 1, 2);
                    if ($model->is_broker === 1) {
                        //刷手佣金取回
                        WB_UserPayRecordHy::createRecord($model->userid, -$model->price, 2, 3);
                    }
                } else if ($model->is_complain === 5) {
                    //刷手佣金取回
                    WB_UserPayRecordHy::createRecord($model->userid, $model->price, 1, 2);
                    //商户账号拨款
                    WB_UserPayRecord::createRecord($model->taskuserid, -MTools::getTaskPrice($taskmodel->task_price_id), 2, 9);
                }
            }
            $trans->commit();
            return true;
        } catch (Exception $ex) {
            $trans->rollBack();
            throw new \yii\web\NotFoundHttpException;
        }
    }

}
